<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue学习使用</title>
  <!-- 第1步： 引入vue库文件 -->
  <script src="./js/vue.js"></script>
</head>

<body>
  <!-- 第2步：挂载点 -->
  <div id="app">
    <table border="1" width="600">
      <tr>
        <th>序号</th>
        <th>名称</th>
        <th>单价</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="item,index in carts">
        <td>{{index+1}}</td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>
          <button @click="setNum(1,index)">+++</button>
          <input type="number" v-model="item.num">
          <button @click="setNum(-1,index)">---</button>
        </td>
        <td>
          <button @click="del(index)">删除</button>
        </td>
      </tr>
    </table>
    <hr>
    <h3>
      合计：
      {{totalPrice}}
    </h3>

  </div>

  <!-- 第3步：实例化vue -->
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        carts: [
          { id: 1, name: '小米12pro', price: 1, num: 1 },
          { id: 2, name: '华为手机', price: 2, num: 1 },
          { id: 3, name: '水果手机', price: 3, num: 1 },
        ]
      },
      methods: {
        setNum(n, index) {
          this.carts[index].num += n
          this.carts[index].num = Math.min(3, Math.max(1, this.carts[index].num))
        },
        del(index) {
          confirm('确定删除') && this.carts.splice(index, 1)
        }
      },
      // 计算属性
      computed: {
        totalPrice() {
          return this.carts.reduce((prev, { price, num }) => {
            prev += price * num
            return prev
          }, 0)
        }
      }
    })
  </script>

</body>

</html>